<?php
namespace app\common;

class TokenGenerator
{
    protected $randChar = '1234567890abcdefghijklmnopqrstuvwxyz';

    protected $markAccountToken = 'acc';

    protected $markPlanToken = 'plan';

    protected $markPageToken = 'page';

    public function generateRandString($len)
    {
        $rnd_str='';
        if( !is_numeric($len) ){
            return false;
        }

        for($i = 0; $i < $len; $i++){
            $pos_str = rand(0, strlen($this->randChar)-1);
            $rnd_str.= substr($randChar, $pos_str, 1);
        }

        return $rnd_str;
    }

    public function generateAccountToken($addition)
    {
          if(!is_string($addition)){
              return false;
          }

          return $this->generateRandString(16);
    }

    public function generatePlanToken($addition)
    {
        if(!is_string($addition)){
            return false;
        }
        return $this->generateRandString(16);
    }

    public function generatePageToken($addition)
    {
        //uuid TokenGenerator
        //32bit of time
        if(!is_string($addition)){
            return false;
        }

        $micro_time = int($this->getMillisecond());
        $bin_micro_time = pack("N*", $micro_time);
        $hex_micro_time = bin2hex($bin_micro_time);

        //ip值,每隔8个比特算一次
        $user_ip = $_SERVER['REMOTE_ADDR'];
        $array_user_ip = explode('.', $user_ip);
        $hex_user_ip = '';
        foreach($array_user_ip as $aui){
            $hex_user_ip.= base_convert($aui, '10', '16');
        }
        //addtion的值
        $hex_addtion = bin2hex($addition);

        //random hex
        $rnd_hex = bin2hex($this->generateRandString(16));

        return $hex_micro_time.'-'.$hex_user_ip.'-'.$hex_addtion.'-'.$rnd_hex;
    }

    private function getMillisecond()
    {
        $time = explode(' ', microtime());
        $time = $time[1] . ($time[0] * 1000);
        $time2 = explode(".", $time);
        $time = $time2[0];
        return $time;
    }


}
